package com.yc.upload.web;

import com.yc.common.vo.Result;
import com.yc.upload.bean.UploadProperties;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
public class UploadController {

    @Resource
    UploadProperties uploadProperties;

    @RequestMapping("upload")
    public Result upload(
            @RequestParam("file") MultipartFile file,
            String webPath) throws IOException {
        final String disPath = uploadProperties.getMapping().get(webPath);
        if (disPath == null) {
            return Result.failure("不能上传文件到该路径:" + webPath);
        }
        String filename = file.getOriginalFilename();
        // 获取文件名后缀
        final int i = filename.lastIndexOf(".");
        String suffix = "";
        if (i > -1) {
            suffix = filename.substring(i);
        }
        //  随机文件名
        filename = UUID.randomUUID().toString().replaceAll("-","");
        filename += suffix;
        // 构建web路径 + 文件名
        webPath += "/" + filename;
        File diskFile = new File(disPath + "/" + filename);
        file.transferTo(diskFile);
        return Result.success("文件上传成功!", webPath);
    }

    @PostMapping("uploads")
    public List<Result> uploads(
            @RequestParam("file") MultipartFile[] files, String webPath){
        List<Result> ret = new ArrayList<>();
        for (MultipartFile file : files) {
            try {
                final Result res = upload(file, webPath);
                ret.add(res);
            } catch (IOException e) {
                ret.add(Result.failure("文件上传失败!", file.getOriginalFilename()));
            }
        }
        return ret;
    }

    @RequestMapping("upload/config")
    public Map<?, ?> getConfig() {
        return uploadProperties.getMapping();
    }

    @ExceptionHandler(IOException.class)
    Result handleIOException(IOException e){
        e.printStackTrace();
        return Result.failure("文件上传失败");
    }
}
